package cn.intotw.pp.decode;

import cn.intotw.pp.constants.Constant;
import cn.intotw.pp.entity.PPProtocolFrame;
import cn.intotw.pp.entity.request.ServerBaseReq;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author Chenxiang
 * @Description: 消息转换器
 * @create 2018/8/20 15:56
 */
public class MessageDecoder extends MessageToMessageDecoder<PPProtocolFrame> {

    protected void decode(ChannelHandlerContext channelHandlerContext, PPProtocolFrame ppProtocolFrame, List<Object> list) throws Exception {
        byte[] contents=ppProtocolFrame.getContent();
        String req=new String(contents,"UTF-8");
        ServerBaseReq serverBaseReq = parseReq(req);
        list.add(serverBaseReq);
    }

    private ServerBaseReq parseReq(String req) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        String[] reqs=req.split(Constant.REQ_SPLIT);
        String head=reqs[0];
        String body=reqs[1];

        String[] heads=head.split(Constant.REQ_HEAD_SPLIT);
        String[] bodys=body.split(Constant.REQ_BODY_SPLIT);
        Class z=null;
        try {
            z=Class.forName("cn.intotw.pp.entity.request.P10001RequestBean");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw e;
        }
        ServerBaseReq serverBaseReq= (ServerBaseReq) z.newInstance();
        parseHead(serverBaseReq,heads);
        parseBody(serverBaseReq,bodys);
        return serverBaseReq;
    }
    private void parseHead(Object serverReq, String[] heads) throws InvocationTargetException, IllegalAccessException, IntrospectionException {
        Field[] headFields=ServerBaseReq.class.getDeclaredFields();
        for (int i = 0; i < headFields.length; i++) {
            PropertyDescriptor fieldprop = new PropertyDescriptor(headFields[i].getName(), serverReq.getClass());
            fieldprop.getWriteMethod().invoke(serverReq,heads[i]);
        }

    }
    private void parseBody(Object serverReq, String[] body) throws InvocationTargetException, IllegalAccessException, IntrospectionException {
        Field[] headFields=serverReq.getClass().getDeclaredFields();
        for (int i = 0; i < headFields.length; i++) {
            PropertyDescriptor fieldprop = new PropertyDescriptor(headFields[i].getName(), serverReq.getClass());
            fieldprop.getWriteMethod().invoke(serverReq,body[i]);
        }
    }



}